package best.driver.android.common.network;

import android.text.TextUtils;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;

public class ApiObjectRequest<T> extends ApiRequest<T> {
    private Class<T> mTargetClass;
    
    private String jsonKey;
    public void setJsonKey(String jString) {
    	this.jsonKey = jString;
	}
    public ApiObjectRequest(Class<T> cls, Method method) {
        super(method);
        this.mTargetClass = cls;
    }

    @Override
    protected T processJsonResponse(Object response) {
        Gson gson = new Gson();
        JSONObject jsonObject = (JSONObject) response;
        if(jsonObject == null){
        	return null;
        }
        if(!TextUtils.isEmpty(jsonKey) && jsonObject.has(jsonKey)){
        	try {
				JSONObject jObject = jsonObject.getJSONObject(jsonKey);
                if(jObject == null)
                    return null;
				return gson.fromJson(jObject.toString(), mTargetClass);
			} catch (JSONException e) {
				e.printStackTrace();
			}
        	return null;
        }
        
        return gson.fromJson(response.toString(), mTargetClass);
    }

	
}
